package org.ricks.game.prop;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class ItemManager {

    private static final Map<Integer, OperatePropInterface> OPERATION_MAP = new ConcurrentHashMap<>();
    private static volatile boolean initialized = false;

    // 私有构造函数防止实例化
    private ItemManager() {}

    /**
     * 初始化管理器，扫描所有带有AutoRegisterItemType注解的类
     */
    public static synchronized void initialize() {
        if (initialized) {
            return;
        }

        // 使用反射扫描所有带有AutoRegisterItemType注解的类
//        Reflections reflections = new Reflections("your.base.package"); // 需要引入org.reflections库
//        Set<Class<?>> annotatedClasses = reflections.getTypesAnnotatedWith(AutoRegisterItemType.class);
//
//        for (Class<?> clazz : annotatedClasses) {
//            if (OperatePropInterface.class.isAssignableFrom(clazz)) {
//                try {
//                    AutoRegisterItemType annotation = clazz.getAnnotation(AutoRegisterItemType.class);
//                    int itemType = annotation.value();
//                    OperatePropInterface instance = (OperatePropInterface) clazz.getDeclaredConstructor().newInstance();
//                    OPERATION_MAP.put(itemType, instance);
//                } catch (Exception e) {
//                    System.err.println("Failed to instantiate class: " + clazz.getName() + ", error: " + e.getMessage());
//                }
//            }
//        }

        // 也可以手动注册一些核心类型作为备选
        registerFallbackTypes();

        initialized = true;
    }

    /**
     * 手动注册备选类型（防止某些类无法通过注解扫描）
     */
    private static void registerFallbackTypes() {
        // 这里可以注册一些核心类型
//        if (!OPERATION_MAP.containsKey(Type.GOLD)) {
//            OPERATION_MAP.put(Type.GOLD, new GoldOperate());
//        }
//        if (!OPERATION_MAP.containsKey(Type.PAYDIAMOND)) {
//            OPERATION_MAP.put(Type.PAYDIAMOND, new PayDiamondOperate());
//        }
        // 其他核心类型...
    }

    /**
     * 注册操作实现
     */
    public static void register(int itemType, OperatePropInterface operation) {
        OPERATION_MAP.put(itemType, operation);
    }

    /**
     * 获取操作实现
     */
    public static OperatePropInterface getOperation(int itemType) {
        if (!initialized) {
            initialize();
        }

        OperatePropInterface operation = OPERATION_MAP.get(itemType);
        if (operation == null) {
            throw new IllegalArgumentException("未支持的道具类型: " + itemType);
        }
        return operation;
    }

    /**
     * 获取所有已注册的类型
     */
    public static Set<Integer> getRegisteredTypes() {
        if (!initialized) {
            initialize();
        }
        return OPERATION_MAP.keySet();
    }
}
